#!/bin/bash
# 移除 set -e 以防止脚本因为非关键错误退出
# set -e

# 等待MySQL和Redis启动
echo "等待数据库服务启动..."
until nc -z -v -w30 mysql 3306
do
  echo "等待MySQL启动..."
  sleep 5
done
echo "MySQL已启动"

until nc -z -v -w30 redis 6379
do
  echo "等待Redis启动..."
  sleep 5
done
echo "Redis已启动"

# 创建必要的目录并设置权限
echo "创建Laravel必要目录..."
mkdir -p /www/cert_manager/deploy/backend/storage/{app,framework/{cache,sessions,views},logs}
mkdir -p /www/cert_manager/deploy/backend/bootstrap/cache

echo "设置目录权限..."
if [ -d "/www/cert_manager/deploy/backend/storage" ]; then
    chown -R www-data:www-data /www/cert_manager/deploy/backend/storage
    chmod -R 775 /www/cert_manager/deploy/backend/storage
    echo "storage目录权限设置完成"
else
    echo "警告: storage目录不存在"
fi

if [ -d "/www/cert_manager/deploy/backend/bootstrap/cache" ]; then
    chown -R www-data:www-data /www/cert_manager/deploy/backend/bootstrap/cache  
    chmod -R 775 /www/cert_manager/deploy/backend/bootstrap/cache
    echo "bootstrap/cache目录权限设置完成"
else
    echo "警告: bootstrap/cache目录不存在"
fi

# 进入后端目录
if [ -d "/www/cert_manager/deploy/backend" ]; then
    cd /www/cert_manager/deploy/backend
    echo "进入后端目录: $(pwd)"
else
    echo "错误: 后端目录不存在，跳过Laravel初始化"
    echo "启动Supervisor..."
    /usr/bin/supervisord -c /etc/supervisor/conf.d/supervisord.conf
    exit 0
fi

# Composer依赖管理
echo "检查Composer依赖状态..."
if [ -f "composer.json" ]; then
    # 检查是否需要安装依赖
    need_composer_install=false
    composer_reason=""
    
    if [ ! -d "vendor" ]; then
        need_composer_install=true
        composer_reason="vendor目录不存在"
    elif [ ! -f "composer.lock" ]; then
        need_composer_install=true
        composer_reason="composer.lock文件不存在"
    elif [ "composer.json" -nt "composer.lock" ]; then
        need_composer_install=true
        composer_reason="composer.json已更新"
    elif [ "composer.lock" -nt "vendor" ]; then
        need_composer_install=true
        composer_reason="composer.lock比vendor目录新"
    elif [ ! -d "vendor/composer" ] || [ ! -f "vendor/autoload.php" ]; then
        need_composer_install=true
        composer_reason="关键vendor文件缺失"
    else
        echo "Composer依赖状态良好，跳过安装"
    fi
    
    if [ "$need_composer_install" = true ]; then
        echo "需要安装Composer依赖: $composer_reason"
        
        # 执行composer install并处理输出
        composer_output=$(composer install --no-dev --optimize-autoloader --no-interaction 2>&1) || {
            echo "警告: Composer依赖安装失败，但继续执行..."
            echo "$composer_output"
        }
        
        # 处理Composer输出，转换为中文并简化
        echo "$composer_output" | while IFS= read -r line; do
            case "$line" in
                *"Installing dependencies from lock file"*)
                    echo "  ✓ 从锁定文件安装依赖..."
                    ;;
                *"Verifying lock file contents"*)
                    echo "  ✓ 验证依赖兼容性..."
                    ;;
                *"Nothing to install, update or remove"*)
                    echo "  ✓ 依赖已是最新，无需更新"
                    ;;
                *"Generating optimized autoload files"*)
                    echo "  ✓ 生成优化的自动加载文件..."
                    ;;
                *"packages you are using are looking for funding"*)
                    # 隐藏资助信息
                    ;;
                *"Use the"*"composer fund"*"command"*)
                    # 隐藏资助命令提示
                    ;;
                *"Warning: The lock file is not up to date"*)
                    echo "  ⚠ 提示：依赖锁定文件可能不是最新版本"
                    ;;
                *"error"*|*"Error"*|*"ERROR"*)
                    echo "  ✗ 错误：$line"
                    ;;
                *)
                    # 其他重要信息保持原样但添加缩进
                    if [[ -n "$line" && ! "$line" =~ ^[[:space:]]*$ && ! "$line" =~ ^[0-9]+/[0-9]+ ]]; then
                        echo "    $line"
                    fi
                    ;;
            esac
        done
    else
        echo "使用现有Composer依赖，节省时间"
    fi
else
    echo "警告: composer.json不存在，跳过依赖嬉装"
fi

# 生成应用密钥
if [ -f ".env.example" ] && [ ! -f ".env" ]; then
    echo "复制环境配置文件..."
    cp .env.example .env
fi

if [ -f ".env" ] && [ -f "artisan" ]; then
    echo "生成应用密钥..."
    php artisan key:generate --force || echo "警告: 应用密钥生成失败"
    
    # 生成JWT密钥
    echo "生成JWT密钥..."
    php artisan jwt:secret --force || echo "警告: JWT密钥生成失败"
    
    # 运行数据库迁移
    echo "运行数据库迁移..."
    php artisan migrate --force || echo "警告: 数据库迁移失败"
    
    # 运行数据库种子数据（安装时必须执行）
    echo "运行数据库种子数据..."
    php artisan db:seed --force || echo "警告: 数据库种子失败"
    
    # 清理缓存
    echo "清理Laravel缓存..."
    php artisan config:clear || echo "警告: 配置缓存清理失败"
    php artisan cache:clear || echo "警告: 应用缓存清理失败"  
    php artisan route:clear || echo "警告: 路由缓存清理失败"
    php artisan view:clear || echo "警告: 视图缓存清理失败"
    
    # 优化
    echo "优化Laravel缓存..."
    php artisan config:cache || echo "警告: 配置缓存失败"
    php artisan route:cache || echo "警告: 路由缓存失败"
    php artisan view:cache || echo "警告: 视图缓存失败"
    
    # 创建符号链接
    echo "创建存储符号链接..."
    php artisan storage:link || echo "警告: 符号链接创建失败"
else
    echo "警告: .env文件或artisan不存在，跳过Laravel初始化"
fi

echo "Laravel初始化完成，启动Supervisor..."

# 确保日志目录存在
mkdir -p /www/cert_manager/php/logs

# 启动Supervisor（在前台运行，不退出）
echo "启动Supervisor进程管理器..."
echo "配置文件: /etc/supervisor/conf.d/supervisord.conf"
echo "日志目录: /www/cert_manager/php/logs/"

/usr/bin/supervisord -c /etc/supervisor/conf.d/supervisord.conf